import json
import os
import sys

from lxml import etree

data = os.getenv('JIANMU_DATA')
file = os.getenv('JIANMU_FILE')
expression = os.getenv('JIANMU_EXPRESSION')

# check
if not expression or expression.isspace():
    print('error: xpath不能为空')
    sys.exit(1)
if file and data:
    print('error: 输入参数 data 和 file 不能同时存在')
    sys.exit(1)
if not file and not data:
    print('error: 输入参数 data 和 file 至少输入一个')
    sys.exit(1)

# parse
if data:
    root = etree.HTML(data)
else:
    if not os.path.exists(file):
        print('error: ' + file + ' not found, please check your filepath')
        sys.exit(1)
    root = etree.parse(file)

# print log
print("xpath表达式：", expression)
print()
print('数据：')
if data:
    print(data)
else:
    with open(file) as f:
        source_file = f.read()
    print(source_file)
print()

# remove xmlns
for elem in root.getiterator():
    if not (isinstance(elem, etree._Comment) or isinstance(elem, etree._ProcessingInstruction)):
        elem.tag = etree.QName(elem).localname

# xpath
try:
    results = root.xpath(expression)
except Exception as e:
    print('error: 未提取到参数，请检查xpath表达式', e)
    sys.exit(1)

# check result
if len(results) != 0 and type(results[0]) == etree._Element:
    print('error: 尚未提取到参数，请检查xpath表达式。')
    print('若想提取标签内容，请使用text()函数，如：/xxx/xxx/text()')
    print('若想提取属性，请使@属性名，如：/xxx/xxx/@yyy')
    print('提取内容：')
    for tag in results:
        print(etree.tostring(tag, encoding='utf-8', pretty_print=True).decode())
    sys.exit(1)

if len(results) == 1:
    result = results[0]
else:
    result = str(json.dumps(results, ensure_ascii=False))
result_data = {
    "result": result
}

json = json.dumps(result_data, ensure_ascii=False, indent=4)
with open('/usr/result_file', 'w') as f:
    f.write(json)
print("结果：")
print('result_file:', json)
